﻿/*
* 创建者：BPChen
* 时间：  2016-06-08
* 描述：  数据模型存放js，统一处理数据交互和后台
* */
angular.module('starter.modules', [])
//主页应用列表
  .factory('HomeApps', function () {
      var homeApps = [
      {
          name: "工作流程",
          icon: "ion-ios-browsers-outline",
          color: "bgcolor_f",
          viewid: 'home-workflow.html',
		  id: ""
      }, /*{
          name: "即时通信",
          icon: "ion-ios-chatboxes-outline",
          color: "bgcolor_g",
          viewid: 'home-wechat.html',
		  id: ""
      },*/ {
          name: "数据统计",
          icon: "ion-ios-pie-outline",
          color: "bgcolor_h",
          viewid: 'home-charts.html',
		  id: ""
      }];

      return {
          all: function () {
              return homeApps;
          },
          remove: function (homeApps) {
              homeApps.splice(homeApps.indexOf(homeApps), 1);
          },
          get: function (homeAppId) {
              for (var i = 0; i < homeApps.length; i++) {
                  if (homeApps[i].id === parseInt(homeAppId)) {
                      return homeApps[i];
                  }
              }
              return null;
          }
      };
   })
   //新闻列表信息
   .factory('News', ['$BPFormatDate', '$BPGetDataItem', '$BPHttp', 'ApiUrl', '$BPTopAlert',function ($BPFormatDate, $BPGetDataItem, $BPHttp, ApiUrl, $BPTopAlert) {
        var newList = {
            records: 0,
            page: 1,
            total: 1,
            moredata: false,
            news: []
        };
	    //方法函数
        function translateData(data, obj) {
            //console.log(data);
            for (var i in data) {
                var item = data[i];
                data[i].CreateDate = $BPFormatDate(item.createDate, 'MM-dd');
                obj.push(data[i]);
            }
        };
		//获取数据
        function getData(page, queryData, obj, callback) {
            $BPHttp.post({
                "url": ApiUrl.newsListApi,
                "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
                "isverify": true,
                "success": function (data) {
                    if (page == 1) {
                        obj.news = [];
                    }
					
                    translateData(data.result.rows, obj.news);
                    obj.records = data.result.records;
                    obj.page = data.result.page;
                    obj.total = data.result.total;
                    if (data.result.page == data.result.total || data.result.total == 0) {
                        
						obj.moredata = false;
						
                    }
                    else {
                        obj.moredata = true;
                    }
                    obj.page = obj.page + 1;
                },
                "error": function () {
                    $BPTopAlert.show({ text: "刷新失败" });
                },
                "finally": function () {
                    callback();
                }
            });
        }
        //返回
        return {
            getList: function () {
                return newList;
            },
			update: function (callback) {
                getData(1, {}, newList, callback);
            },
            add: function (callback) {
                getData(newList.page, {}, newList, callback);
            }
        };
    }])
	.factory('$FormData', ['$BPFormatDate', '$BPGetDataItem', '$BPHttp', 'ApiUrl', '$BPTopAlert',function ($BPFormatDate, $BPGetDataItem, $BPHttp, ApiUrl, $BPTopAlert) {
        var formList = {
            records: 0,
            page: 1,
            total: 1,
            moredata: false,
            items: []
        };
		var FormListSearch = {};//搜索列表数据
	    //方法函数
        function translateData(data, obj) {
            //console.log(data);
            for (var i in data) {
                var item = data[i];
				data[i].CreateDate = $BPFormatDate(item.createDate, 'MM-dd');
				obj.push(data[i]);
            }
        };
		function isEmpty(obj)
		{
			for (var name in obj)
			{
				return false;
			}
			return true;
		};
		//获取数据
        function getData(id,page, queryData, obj, callback) {
			
			var querydata=queryData;
			var querytype="";
			var keyword="";
			if(queryData.keyword)
			{
				keyword=queryData.keyword;
			}
			if(queryData.condition)
			{
				if(queryData.condition=="All")
					querytype="";
				else
					querytype=queryData.condition;
			}
			var redata={ "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData),"relationFormId":id,"condition":querytype,"keyword":keyword };
			console.log(redata);
            $BPHttp.post({
                "url": ApiUrl.geFormDataApi,
                "data": redata,
                "isverify": false,
                "success": function (data) {
                    if (page == 1) {
                        obj.items = [];
                    }
					data.result.rows= data.result.rows.replace(/\r\n/g,"");  
					data.result.rows= data.result.rows.replace(/\n/g,""); 
					data.result.rows=JSON.parse(data.result.rows);
					
					//console.log(obj.moredata);
                    translateData(data.result.rows, obj.items);
					console.log(data.result.records);
                    obj.records = data.result.records;
                    obj.page = data.result.page;
					
                    obj.total = data.result.total;
                    if (data.result.page == data.result.total || data.result.total == 0) {
						//console.log(false);
                        obj.moredata = false;
                    }
                    else {
						//console.log(true);
                        obj.moredata = true;
                    }
					
                    obj.page = obj.page + 1;
					//console.log(obj.page);
                },
                "error": function () {
                    $BPTopAlert.show({ text: "刷新失败" });
                },
                "finally": function () {
                    callback();
                }
            });
        }
        //返回
        return {
            getList: function (relationFormId) {
                return formList;
            },
			update: function (relationFormId,callback) {
                getData(relationFormId,1, {}, formList, callback);
            },
            add: function (relationFormId,callback) {
				console.log(formList.page);
                getData(relationFormId,formList.page, {}, formList, callback);
            },
			getSearchList: function (relationFormId) {
                ListSearch = {
                    records: 0,
                    page: 1,
                    total: 1,
                    moredata: false,
                    items: [],
                    keyword: "",
					searchtype:"All"
                };
                return ListSearch;
            },
			searchData: function (relationFormId) {
                if (ListSearch.keyword == "") {
                    return false;
                }
				console.log(ListSearch);
                getData(relationFormId,1, { "condition": ListSearch.searchtype, "keyword": ListSearch.keyword }, ListSearch, function () { });
            },
			searchDataAdd: function (relationFormId,callback) {
                if (ListSearch.keyword == "") {
                    return false;
                }
                getData(relationFormId,ListSearch.page, { "condition": ListSearch.searchtype, "keyword": ListSearch.keyword }, ListSearch, callback);
            }
        };
    }])
	//通知列表信息
   .factory('Notice', ['$BPFormatDate', '$AreaInfo', '$BPGetDataItem', '$BPHttp', 'ApiUrl', '$BPTopAlert','$BPLocals',function ($BPFormatDate, AreaInfo, $BPGetDataItem, $BPHttp, ApiUrl, $BPTopAlert,$BPLocals) {
        var noticeList = {
            records: 0,
            page: 1,
            total: 1,
            moredata: false,
            notices: {btnNoRead:[],btnRead:[]}
        };
	    //方法函数
        function translateData(data, obj) {
            //console.log(data);
            for (var i in data) {
                var item = data[i];
				data[i].CreateDate = $BPFormatDate(item.createDate, 'MM-dd');
				var ReadListInfo = $BPLocals.getObject('NoticeReadInfo');
				//console.log(isEmpty(ReadListInfo));
				if(isEmpty(ReadListInfo)!=true)
				{
					var filter_id = ReadListInfo.items.map(function (item) { return item.id; });
					if(filter_id.indexOf(data[i].newsId)>=0)
					{
						obj.btnRead.push(data[i]);
					}else{
						obj.btnNoRead.push(data[i]);
					}
				}
				else
				{
					obj.btnNoRead.push(data[i]);
				}
            }
        };
		function isEmpty(obj)
		{
			for (var name in obj)
			{
				return false;
			}
			return true;
		};
		//获取数据
        function getData(page, queryData, obj, callback) {
            $BPHttp.post({
                "url": ApiUrl.noticeListApi,
                "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
                "isverify": true,
                "success": function (data) {
                    if (page == 1) {
                        obj.notices = {btnNoRead:[],btnRead:[]};
                    }
                    translateData(data.result.rows, obj.notices);
                    obj.records = data.result.records;
                    obj.page = data.result.page;
                    obj.total = data.result.total;
                    if (data.result.page == data.result.total || data.result.total == 0) {
                        obj.moredata = false;
                    }
                    else {
                        obj.moredata = true;
                    }
                    obj.page = obj.page + 1;
                },
                "error": function () {
                    $BPTopAlert.show({ text: "刷新失败" });
                },
                "finally": function () {
                    callback();
                }
            });
        }
        //返回
        return {
            getList: function () {
                return noticeList;
            },
			update: function (callback) {
                getData(1, {}, noticeList, callback);
            },
            add: function (callback) {
                getData(noticeList.page, {}, noticeList, callback);
            }
        };
    }])
    //流程列表
    .factory('$WFlows', function () {
    var wflows = {
        "createProcess": {
            name: '发起流程',
            icon: 'ion-ios-folder-outline',
            bgcolor: 'positive-bg',
            viewid: 'flowdesign.html',
			props:0
        }, "flowRoughdraft": {
            name: '草稿流程',
            icon: 'ion-ios-list-outline',
            bgcolor: 'calm-bg',
            viewid: 'flowRoughdraft.html',
			props:0
        }, "myProcess": {
            name: '我的流程',
            icon: 'ion-ios-paper-outline',
            bgcolor: 'balanced-bg',
            viewid: 'flowProcess.html',
			props:0
        }, "befProcess": {
            name: '待办流程',
            icon: 'ion-ios-locked-outline',
            bgcolor: 'energized-bg',
            viewid: 'flowBefProcess.html',
			props:0
        }, "aftProcess": {
            name: '已办流程',
            icon: 'ion-ios-unlocked-outline',
            bgcolor: 'assertive-bg',
            viewid: 'flowAftProcess.html',
			props:0
        }, "delegate": {
            name: '工作委托',
            icon: 'ion-ios-barcode-outline',
            bgcolor: 'royal-bg',
            viewid: 'flowDelegate.html',
			props:0
        }
    };
    return {
        all: function () {
            return wflows;
        },
        get: function (id) {
            return wflows[id];
        }
    };
})
//发起流程
.factory('$FlowDesigns', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //发起流程列表数据
      var flowdesignList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          flowdesigns: []
      };
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].createdate = $BPFormatDate(item.createdate, 'MM-dd');
              obj.push(data[i]);
          }
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowDesignListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.flowdesigns = [];
                  }
                  
                  //var re = JSON.parse(data.result);
                  re = data.result;
                  translateData(re.rows, obj.flowdesigns);
                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
          getList: function () {
              return flowdesignList;
          },
          update: function (callback) {
              getData(1, {}, flowdesignList, callback);
          },
          add: function (callback) {
              getData(flowdesignList.page, {}, flowdesignList, callback);
          },
          get: function (flowId) {
              for (var i = 0; i < flowdesignList.flowdesigns.length; i++) {
                  if (flowdesignList.flowdesigns[i].f_id === flowId) {
                      return flowdesignList.flowdesigns[i];
                  }
              }
              return null;
          },
          editSubmit: function (keyValue, editData, callback) {
              //alert(JSON.stringify(editData));
              $BPHttp.post({
                  "url": ApiUrl.saveFlowDesignApi,
                  "data": {
                      data: JSON.stringify(editData),
                      keyValue: keyValue.toString()
                  },
                  //"data": {editData,keyValue},
                  "isverify": true,
                  "success": function (data) {
                      $BPTopAlert.show({ text: "保存成功！" });
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "保存失败！" });
                  },
                  "finally": function () {
                      callback();
                  }
              });
          },
          remove: function (flowdesign) {
              //console.log(flowdesign.flowId);
              $BPHttp.post({
                  "url": ApiUrl.deleteFlowDesignApi,
                  "data": { "flowId": flowdesign.flowId },
                  "success": function () {
                      for (var i = 0; i < flowdesignList.flowdesigns.length; i++) {
                          if (flowdesignList.flowdesigns[i].f_id === flowdesign.flowId) {
                              flowdesign = flowdesignList.flowdesigns[i];
                          }
                      }
                      flowdesignList.flowdesigns.splice(flowdesignList.flowdesigns.indexOf(flowdesign), 1);
                      flowdesignList.records = flowdesignList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          }
      };
  }])
//草稿流程
.factory('$FlowRoughdrafts', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //草稿流程列表数据
      var flowroughdraftList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          flowroughdrafts: []
      };
	  
	  var keyword="";
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].createDate = $BPFormatDate(item.createDate, 'MM-dd');
              obj.push(data[i]);
          }
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowRoughdraftListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.flowroughdrafts = [];
                  }
                  console.log(data);

                  var re = data.result;

                  translateData(re.rows, obj.flowroughdrafts);
                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
		  setInit:function(){
			  keyword="";
		  },
          getList: function () {
              return flowroughdraftList;
          },
          update: function (callback) {
              getData(1, { "keyword": keyword }, flowroughdraftList, callback);
          },
          add: function (callback) {
              getData(flowroughdraftList.page, { "Keyword": keyword }, flowroughdraftList, callback);
          },
          get: function (flowId) {
              for (var i = 0; i < flowroughdraftList.flowroughdrafts.length; i++) {
                  if (flowroughdraftList.flowroughdrafts[i].Id === flowId) {
                      return flowroughdraftList.flowroughdrafts[i];
                  }
              }
              return null;
          },
		  getSearchList(Search_key, callback){
			  keyword=Search_key;
			  condition="ALL";
			  getData(1, { "Keyword": keyword }, flowroughdraftList, callback);
		  },
          remove: function (flowroughdraft) {
              $BPHttp.post({
                  "url": ApiUrl.deleteFlowRoughdraftApi,
                  "data": { "schemeinfoid": flowroughdraft.id },
                  "success": function () {
                      for (var i = 0; i < flowroughdraftList.flowroughdrafts.length; i++) {
                          if (flowroughdraftList.flowroughdrafts[i].id === flowroughdraft.flowId) {
                              flowroughdraft = flowroughdraftList.flowroughdrafts[i];
                          }
                      }
                      flowroughdraftList.flowroughdrafts.splice(flowroughdraftList.flowroughdrafts.indexOf(flowroughdraft), 1);
                      flowroughdraftList.records = flowroughdraftList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          }
      };
  }])
//我的流程列表
.factory('$Workflows', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //我的流程列表数据
      var workflowList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          workflows: []
      };
	  var keyword="";
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].createDate = $BPFormatDate(item.createDate, 'MM-dd');
              if (data[i].isFinish == 0) {
                  data[i].isFinish = "处理中";
                  data[i].bgcolor = "positive-bg";
              } else if (data[i].isFinish == 1) {
                  data[i].isFinish = "通过完成";
                  data[i].bgcolor = "calm-bg";
              } else if (data[i].isFinish == 2) {
                  data[i].isFinish = "被召回";
                  data[i].bgcolor = "bgcolor_d";
              } else if (data[i].isFinish == 3) {
                  data[i].isFinish = "不通过";
                  data[i].bgcolor = "bgcolor_d";
              } else if (data[i].isFinish == 4) {
                  data[i].isFinish = "被驳回";
                  data[i].bgcolor = "bgcolor_d";
              } else {
                  data[i].isFinish = "暂停";
              }
              if (data[i].wfLevel == 1) {
                  data[i].wfLevel = "重要";
              } else if (data[i].wfLevel == 2) {
                  data[i].wfLevel = "普通";
              } else if (data[i].wfLevel == 3) {
                  data[i].wfLevel = "一般";
              }
              obj.push(data[i]);
          }
          //alert(JSON.stringify(data));
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowProcessListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.workflows = [];
                  }
                  //console.log(data.result);
                  var re = data.result;
                  //console.log(re.rows[0].code);

                  translateData(re.rows, obj.workflows);
                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
		  setInit:function(){
			  keyword="";
		  },
          getList: function () {
              return workflowList;
          },
          update: function (callback) {
              getData(1, { "Keyword": keyword }, workflowList, callback);
          },
          add: function (callback) {
              getData(workflowList.page, { "Keyword": keyword }, workflowList, callback);
          },
		  getSearchList(Search_key, callback){
			  keyword=Search_key;
			  getData(1, { "Keyword": keyword }, workflowList, callback);
		  },
          get: function (flowId) {
              for (var i = 0; i < workflowList.workflows.length; i++) {
                  if (workflowList.workflows[i].f_id === flowId) {
                      return workflowList.workflows[i];
                  }
              }
              return null;
          },
          remove: function (workflow) {
              $BPHttp.post({
                  "url": ApiUrl.deleteWorkflowApi,
                  "data": { "flowId": workflow.flowId },
                  "success": function () {
                      for (var i = 0; i < workflowList.workflows.length; i++) {
                          if (workflowList.workflows[i].id === workflow.flowId) {
                              workflow = workflowList.workflows[i];
                          }
                      }
                      workflowList.workflows.splice(workflowList.workflows.indexOf(workflow), 1);
                      workflowList.records = workflowList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          }
      };
  }])
//代办流程
.factory('$FlowBefProcesss', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //代办流程列表数据
      var flowbefprocessList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          flowbefprocesss: []
      };
	  var keyword="";
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].createDate = $BPFormatDate(item.createDate, 'MM-dd');
              if (data[i].wfLevel == 1) {
                  data[i].wfLevel = "重要";
              } else if (data[i].wfLevel == 2) {
                  data[i].wfLevel = "普通";
              } else if (data[i].wfLevel == 3) {
                  data[i].wfLevel = "一般";
              }
              obj.push(data[i]);
          }
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowBefProcessListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.flowbefprocesss = [];
                  }
                  var re = data.result;

                  translateData(re.rows, obj.flowbefprocesss);
                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
		  setInit:function(){
			  keyword="";
		  },
          getList: function () {
              return flowbefprocessList;
          },
          update: function (callback) {
              getData(1, { "Keyword": keyword }, flowbefprocessList, callback);
          },
          add: function (callback) {
              getData(flowbefprocessList.page, { "Keyword": keyword }, flowbefprocessList, callback);
          },
          get: function (flowId) {
              for (var i = 0; i < flowbefprocessList.flowbefprocesss.length; i++) {
                  if (flowbefprocessList.flowbefprocesss[i].Id === flowId) {
                      return flowbefprocessList.flowbefprocesss[i];
                  }
              }
              return null;
          },
		  getSearchList(Search_key, callback){
			  keyword=Search_key;
			  getData(1, { "Keyword": keyword }, flowbefprocessList, callback);
		  },
          remove: function (flowbefprocess) {
              $BPHttp.post({
                  "url": ApiUrl.deleteFlowBefProcessApi,
                  "data": { "flowId": flowbefprocess.flowId },
                  "success": function () {
                      for (var i = 0; i < flowbefprocessList.flowbefprocesss.length; i++) {
                          if (flowbefprocessList.flowbefprocesss[i].Id === flowbefprocess.flowId) {
                              flowbefprocess = flowbefprocessList.flowbefprocesss[i];
                          }
                      }
                      flowbefprocessList.flowbefprocesss.splice(flowbefprocessList.flowbefprocesss.indexOf(flowbefprocess), 1);
                      flowbefprocessList.records = flowbefprocessList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          },
          editSubmit: function (editData, callback) {
              //alert(JSON.stringify(editData));
              $BPHttp.post({
                  "url": ApiUrl.saveFlowBefProcessApi,
                  "data": editData,
                  //"isverify": true,
                  "success": function (data) {
                      $BPTopAlert.show({ text: "保存成功！" });
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "保存失败！" });
                  },
                  "finally": function () {
                      callback();
                  }
              });
          }
      };
  }])
//已办流程
.factory('$FlowAftProcesss', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //已办流程列表数据
      var flowaftprocessList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          flowaftprocesss: []
      };
	  var keyword="";
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].createDate = $BPFormatDate(item.createDate, 'MM-dd');
              if (data[i].f_wflevel == 1) {
                  data[i].f_wflevel = "重要";
              } else if (data[i].f_wflevel == 2) {
                  data[i].f_wflevel = "普通";
              } else if (data[i].f_wflevel == 3) {
                  data[i].f_wflevel = "一般";
              }
              if (data[i].isFinish == 0) {
                  data[i].isFinish = "处理中";
              } else if (data[i].isFinish == 1) {
                  data[i].isFinish = "通过完成";
              } else if (data[i].isFinish == 2) {
                  data[i].isFinish = "被召回";
              } else if (data[i].isFinish == 3) {
                  data[i].isFinish = "不通过";
              } else if (data[i].isFinish == 4) {
                  data[i].isFinish = "被驳回";
              }
              obj.push(data[i]);
          }
          //console.log(JSON.stringify(data[i]));
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowAftProcessListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.flowaftprocesss = [];
                  }
                  var re = data.result;
                  translateData(re.rows, obj.flowaftprocesss);

                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
		  setInit:function(){
			  keyword="";
		  },
          getList: function () {
              return flowaftprocessList;
          },
          update: function (callback) {
              getData(1, { "Keyword": keyword }, flowaftprocessList, callback);
          },
          add: function (callback) {
              getData(flowaftprocessList.page, { "Keyword": keyword }, flowaftprocessList, callback);
          },
          get: function (flowId) {
              console.log(flowaftprocessList.flowaftprocesss.length);
              for (var i = 0; i < flowaftprocessList.flowaftprocesss.length; i++) {
                  if (flowaftprocessList.flowaftprocesss[i].f_id === flowId) {
                      return flowaftprocessList.flowaftprocesss[i];
                  }
              }
              return null;
          },
		  getSearchList(Search_key, callback){
			  keyword=Search_key;
			  getData(1, { "Keyword": keyword }, flowaftprocessList, callback);
		  },
          remove: function (flowaftprocess) {

              $BPHttp.post({
                  "url": ApiUrl.deleteFlowAftProcessApi,
                  "data": { "flowId": flowaftprocess.flowId },
                  "success": function () {
                      for (var i = 0; i < flowaftprocessList.flowaftprocesss.length; i++) {
                          if (flowaftprocessList.flowaftprocesss[i].id === flowaftprocess.flowId) {
                              flowaftprocess = flowaftprocessList.flowaftprocesss[i];
                          }
                      }
                      flowaftprocessList.flowaftprocesss.splice(flowaftprocessList.flowaftprocesss.indexOf(flowaftprocess), 1);
                      flowaftprocessList.records = flowaftprocessList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          }
      };
  }])
//工作委托
.factory('$FlowDelegates', ['$BPFormatDate', '$BPHttp', 'ApiUrl', '$BPTopAlert', '$BPGetDataItem',
  function ($BPFormatDate, $BPHttp, ApiUrl, $BPTopAlert, $BPGetDataItem) {
      //发起流程列表数据
      var flowdelegateList = {
          records: 0,
          page: 1,
          total: 1,
          moredata: false,
          flowdelegates: []
      };
      //方法函数
      function translateData(data, obj) {
          for (var i in data) {
              var item = data[i];
              data[i].CreateDate = $BPFormatDate(item.CreateDate, 'MM-dd');
              data[i].BeginDate = $BPFormatDate(item.BeginDate, 'MM-dd');
              data[i].EndDate = $BPFormatDate(item.EndDate, 'MM-dd');
              obj.push(data[i]);
          }
      };
      //获取数据方法
      function getData(page, queryData, obj, callback) {
          $BPHttp.post({
              "url": ApiUrl.flowDelegateListApi,
              "data": { "page": page, "rows": 10, "sidx": "CreateDate", "sord": "desc", "queryData": JSON.stringify(queryData) },
              "isverify": true,
              "success": function (data) {
                  if (page == 1) {
                      obj.flowdelegates = [];
                  }
                  //console.log(data.result);

                  var re = data.result;
                  translateData(re.rows, obj.flowdelegates);
                  obj.records = re.records;
                  obj.page = re.page;
                  obj.total = re.total;
                  if (re.page == re.total || re.total == 0) {
                      obj.moredata = false;
                  }
                  else {
                      obj.moredata = true;
                  }
                  obj.page = obj.page + 1;
              },
              "error": function () {
                  $BPTopAlert.show({ text: "刷新失败" });
              },
              "finally": function () {
                  callback();
              }
          });
      }
      return {
          getList: function () {
              return flowdelegateList;
          },
          update: function (callback) {
              getData(1, {}, flowdelegateList, callback);
          },
          add: function (callback) {
              getData(flowdelegateList.page, {}, flowdelegateList, callback);
          },
          get: function (flowId) {
              for (var i = 0; i < flowdelegateList.flowdelegates.length; i++) {
                  if (flowdelegateList.flowdelegates[i].f_id === flowId) {
                      return flowdelegateList.flowdelegates[i];
                  }
              }
              return null;
          },
          editSubmit: function (editData, callback) {
              //alert(JSON.stringify(editData));
              $BPHttp.post({
                  "url": ApiUrl.saveFlowDelegateApi,
                  "data": editData,
                  //"isverify": true,
                  "success": function (data) {
                      $BPTopAlert.show({ text: "保存成功！" });
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "保存失败！" });
                  },
                  "finally": function () {
                      callback();
                  }
              });
          },
          remove: function (flowdelegate) {
              console.log(flowdelegate.flowId);
              $BPHttp.post({
                  "url": ApiUrl.deleteFlowDeleteApi,
                  "data": { "flowId": flowdelegate.flowId },
                  "success": function () {
                      for (var i = 0; i < flowdelegateList.flowdelegates.length; i++) {
                          if (flowdelegateList.flowdelegates[i].f_id === flowdelegate.flowId) {
                              flowdelegate = flowdelegateList.flowdelegates[i];
                          }
                      }
                      flowdelegateList.flowdelegates.splice(flowdelegateList.flowdelegates.indexOf(flowdelegate), 1);
                      flowdelegateList.records = flowdelegateList.records - 1;
                  },
                  "error": function () {
                      $BPTopAlert.show({ text: "删除失败！" });
                  }
              });
          }
      };
  }])
//即时通讯
    .factory('$IM', ['$q', 'UserInfo', 'SignalrUrl', '$BPLoadJs', '$BPFormatDate', function ($q, UserInfo, SignalrUrl, $BPLoadJs, $BPFormatDate) {
        var imServer = {
            "userInfo": UserInfo.get(),
            "isIMLoaded": false,
            "fnDisconnected": null,

            "updateUserStatus": function (userId, isOnLine) { },//刷用户在线状态0离线。1在线
            "revMessage": function (formUser, message, dateTime) { },//接收消息
            "revGroupMessage": function (userId, toGroup, message, dateTime) { },//接收群组消息
            "afterLinkSuccess": function () { },//连接服务成功后
            "disconnected": function () { },//断开连接后

            "userAllList": [],
            "userAllListByDepartment": {},
            "lastUserList": {},
            "lastUserArray": [],
            "currentUserId": "",
            "messages": []

        };

        function LastUserListToArray() {
            imServer.lastUserArray = [];
            
            for (var i in imServer.lastUserList) {
                imServer.lastUserList[i].IMCreateTime = $BPFormatDate(imServer.lastUserList[i].IMCreateTime, "MM-dd hh:mm");
                imServer.lastUserArray.push(imServer.lastUserList[i]);
            }
        }

        return {
            "init": function (fnDisconnected, $scope) {
                imServer.fnDisconnected = fnDisconnected;
                var deferred = $q.defer();
                console.log(imServer.isIMLoaded, "isIMLoaded -mim");
                if (!imServer.isIMLoaded) {
                    $BPLoadJs(SignalrUrl + "/hubs").then(
                        function (data) {
                            if (data == "success") {
                                console.log(data, "js获取成功mim");
                                $.connection.hub.url = SignalrUrl;
                                $.connection.hub.qs = { "userId": imServer.userInfo.userid };
                                var chat = $.connection.ChatsHub;

                                //注册客户端方法
                                //更新联系人列表
                                chat.client.IMUpdateUserList = function (userAllList, onLineUserList) {
                                    imServer.userAllListByDepartment = {};
                                    imServer.userAllList = userAllList;
                                    for (var Id in userAllList) {
                                        var item = userAllList[Id];
                                        if (Id != imServer.userInfo.userid) {
                                            if (imServer.userAllListByDepartment[item.DepartmentId] == undefined) {
                                                imServer.userAllListByDepartment[item.DepartmentId] = {};
                                                imServer.userAllListByDepartment[item.DepartmentId].DepartmentName = item.DepartmentId;
                                                if (item.UserOnLine == 1) {
                                                    imServer.userAllListByDepartment[item.DepartmentId].onLineNum = 1;
                                                }
                                                else {
                                                    imServer.userAllListByDepartment[item.DepartmentId].onLineNum = 0;
                                                }
                                                imServer.userAllListByDepartment[item.DepartmentId].UserList = [];
                                                imServer.userAllListByDepartment[item.DepartmentId].UserList.push(item);
                                            }
                                            else {
                                                if (item.UserOnLine == 1) {
                                                    imServer.userAllListByDepartment[item.DepartmentId].onLineNum++;
                                                }
                                                imServer.userAllListByDepartment[item.DepartmentId].UserList.push(item);
                                            }
                                        }
                                    };
                                    if ($scope != null && $scope != undefined) {
                                        $scope.$apply();
                                    }
                                    console.log(imServer.userAllListByDepartment);
                                }
                                //刷新最近的联系人
                                chat.client.IMUpdateLastUser = function (lastUserList) {
                                    imServer.lastUserList = lastUserList;
                                    LastUserListToArray();
                                    if ($scope != null && $scope != undefined) {
                                        $scope.$apply();
                                    }

                                }
                                //刷新用户在线状态
                                chat.client.IMUpdateUserStatus = function (userId, isOnLine) {
                                    imServer.userAllList[userId].UserOnLine = isOnLine;
                                    if ($scope != null && $scope != undefined) {
                                        $scope.$apply();
                                    }
                                }
                                //接收消息
                                chat.client.RevMessage = function (formUser, message, dateTime) {
                                    if (imServer.currentUserId != "") {
                                        var msgContent = {
                                            "Content": message,
                                            "CreateDate": dateTime,
                                            "SendId": formUser
                                        };
                                        imServer.messages.push(msgContent);
                                        imServer.IMUpdateMessageStatus(imServer.currentUserId);
                                        if (imServer.lastUserList[imServer.currentUserId] == undefined) {
                                            imServer.lastUserList[imServer.currentUserId] = {};
                                            imServer.lastUserList[imServer.currentUserId].UnReadNum = 0;
                                            imServer.lastUserList[imServer.currentUserId].OtherId = imServer.currentUserId;
                                            imServer.lastUserList[imServer.currentUserId].SendId = formUser;
                                            var id = (formUser == imServer.userInfo.userid ? imServer.currentUserId : formUser);
                                            imServer.lastUserList[imServer.currentUserId].UserId = id;
                                        }
                                        imServer.lastUserList[imServer.currentUserId].IMCreateTime = dateTime;
                                        imServer.lastUserList[imServer.currentUserId].IMContent = message;

                                    } else {
                                        if (imServer.lastUserList[formUser] == undefined) {
                                            imServer.lastUserList[formUser] = {};
                                            imServer.lastUserList[formUser].UnReadNum = 0;
                                        }
                                        imServer.lastUserList[formUser].IMContent = message;
                                        imServer.lastUserList[formUser].OtherId = formUser;
                                        imServer.lastUserList[formUser].SendId = formUser;

                                        imServer.lastUserList[formUser].IMCreateTime = dateTime;
                                        imServer.lastUserList[formUser].UserId = imServer.userInfo.userid;

                                        imServer.lastUserList[formUser].UnReadNum++;
                                    }


                                    LastUserListToArray();
                                    if ($scope != null && $scope != undefined) {
                                        $scope.$apply();
                                        $scope.scrollBottom();
                                    }
                                }


                                //开启连接
                                $.connection.hub.start().done(function () {
                                    console.log("连接成功hub");
                                    //连接成功后注册方法
                                    imServer.IMGetMsgList = function (page, rownum, sendId) {//获取与某用户的消息列表
                                        var deferredGetMsglist = $q.defer();
                                        var pagination = { rows: rownum, page: page, sidx: 'CreateDate', sord: 'desc' }
                                        chat.server.getMsgList(pagination, sendId).done(function (resdata) {
                                            var data = [], i = 0;
                                            for (i = resdata.length, i >= 0; i--;) {
                                                data.push(resdata[i]);
                                            }
                                            imServer.messages = data;
                                            console.log(data);
                                            deferredGetMsglist.resolve(data);
                                        });
                                        return deferredGetMsglist.promise;
                                    };
                                    imServer.IMUpdateMessageStatus = function (sendId) {//更新消息状态
                                        return chat.server.updateMessageStatus(sendId);
                                    };
                                    imServer.IMSendToOne = function (toUser, message) {//发送消息
                                        chat.server.imSendToOne(toUser, message);
                                    };

                                    imServer.isIMLoaded = true;
                                    deferred.resolve({ "code": "success", "msg": "即时通讯连接成功" });
                                });

                                //断开连接后
                                $.connection.hub.disconnected(function () {
                                    imServer.isIMLoaded = false;
                                    if (imServer.fnDisconnected != null) {
                                        imServer.fnDisconnected();
                                    }
                                });
                            }
                            else {
                                console.log(data, "连接成功服务端未开启mim");
                                deferred.resolve({ "code": "error", "msg": "服务端未开启" });
                            }
                        }
                    );
                }
                else {
                    deferred.resolve({ "code": "success", "msg": "即时通讯连接成功" });
                }

                return deferred.promise;
            },
            "getServer": function () {
                return imServer;
            }
        }
    }])
  //首页公告
  .factory('Announces', ['$BPHttp', 'ApiUrl', function ($BPHttp, ApiUrl) {
      var baseInfo = {
          announcesListInfo: [],//列表
		  moduleListInfo:[]
      };
      return {
          init: function () {
              $BPHttp.post({
                  "url": ApiUrl.getAnnouncesListApi,
                  "isverify": true,
                  "success": function (data) {
                      baseInfo.announcesListInfo = data.result.rows;
					  baseInfo.moduleListInfo = data.result.modules;
                  }
              });
          },
          getList: function () {
              var data = [];
              for (var i in baseInfo.announcesListInfo) {
                  var item = baseInfo.announcesListInfo[i];
				  data.push(item);
              }
              return data;
          }
      };
  }])
  //我的账号信息
  .factory('UserInfo', ['$BPLocals','ApiUrl', function ($BPLocals,ApiUrl) {
      var userInfo = {
          userid: "",
          account: "",
          password: "",
          realname: "",
          headicon: "",
          gender: "",
          organizeid: "",
          organizename: "",
          departmentid: "",
          departmentname: "",
          dutyid: "",
          dutyname: "",
          postid: "",
          postname: "",
          roleid: "",
          rolename: "",
          managerid: "",
          manager: "",
          description: "",
          mobile: "",
          telephone: "",
          email: "",
          oicq: "",
          wechat: "",
          msn: "",
          token: "",
          isLogin: false,
      };
      return {
          get: function () {
              var newUserInfo = $BPLocals.getObject('userInfo');
              if (newUserInfo.isLogin == undefined) {
                  userInfo.isLogin = false;
                  userInfo.token = "";
              }
              ionic.extend(userInfo, userInfo, newUserInfo || {});
              return userInfo;
          },
		  update :function(mobile,telephone,email,wechat,oicq,msn)
		  {
			  var newUserInfo = $BPLocals.getObject('userInfo');
			  newUserInfo.mobile=mobile;
			  newUserInfo.telephone=telephone;
			  newUserInfo.email=email;
			  newUserInfo.wechat=wechat;
			  newUserInfo.oicq=oicq;
			  newUserInfo.msn=msn;
			  $BPLocals.setObject('userInfo', newUserInfo);
		  },
          set: function (data, token, isLogin) {
              data.headicon = ApiUrl.webRoot+data.headicon;//(data.headicon == undefined ? userInfo.headicon : data.headicon);
              ionic.extend(userInfo, userInfo, data || {});
              userInfo.token = token;
              userInfo.isLogin = isLogin;
              $BPLocals.setObject('userInfo', userInfo);
          },
          clear: function () {
              userInfo.isLogin = false;
              userInfo.token = "";
              $BPLocals.setObject('userInfo', {});
          }
      };
  }])
  //行政区域数据
  .factory('$AreaInfo', ['$BPHttp', 'ApiUrl','$BPLocals', function ($BPHttp, ApiUrl,$BPLocals) {
      var areaInfo = {};
	  isEmpty = function(obj)
	  {
			for (var name in obj)
			{
				return false;
			}
			return true;
	  };
      return {
          init: function () {
			  var newareaInfo = $BPLocals.getObject('areaInfo');
			  if(isEmpty(newareaInfo)==false)
			  {
				  //console.log(areaInfo);
				  areaInfo=newareaInfo;
			  }
			  else{
				  $BPHttp.post({
					  "url": ApiUrl.areaListApi,
					  "isverify": true,
					  "success": function (data) {
						  areaInfo = data.result;
						  $BPLocals.setObject('areaInfo', areaInfo);
					  }
				  });
			  }
			  
          },
		  getProvinceData: function () {
			  var ProvinceData=[];
			  for(var i in areaInfo)
			  {
				  var Item={};
				  Item.id=areaInfo[i].areaID;
				  Item.name=areaInfo[i].areaName;
				  ProvinceData.push(Item);
			  }
			  return ProvinceData;
		  },
		  getCityData: function (provinceId) {
			  var CityData=[];
			  var provinceID=areaInfo[provinceId].cityInfo;
			  for(var i in provinceID)
			  {
				  var Item={};
				  Item.id=provinceID[i].cityID;
				  Item.name=provinceID[i].cityName;
				  CityData.push(Item);
			  }
			  return CityData;
		  },
		  getAreaData: function (provinceId,cityId) {
			  var AreaData=[];
			  var cityID=areaInfo[provinceId].cityInfo[cityId].childInfo;
			  for(var i in cityID)
			  {
				  
				  var Item={};
				  Item.id=cityID[i].itemID;
				  Item.name=cityID[i].itemName;
				  AreaData.push(Item);
			  }
			  
			  return AreaData;
		  },
          getProvinceName: function (provinceId) {
              return areaInfo[provinceId].areaName;
          },
          getCityName: function (provinceId, cityId) {
              return areaInfo[provinceId].cityInfo[cityId].cityName;
          }
      };
  }])
  //基础信息
  .factory('$BaseInfo', ['$BPHttp', 'ApiUrl', function ($BPHttp, ApiUrl) {
      var baseInfo = {
          userListInfo: [],//用户列表
		  userAllListByDepartment:{}
      };
      return {
          init: function () {
              $BPHttp.post({
                  "url": ApiUrl.getUserListApi,
                  "isverify": true,
                  "success": function (data) {
                      baseInfo.userListInfo = data.result;
                  }
              });
          },
		  getUserList:function(){
			 return  baseInfo.userListInfo;
		  },
          getUserInfoList: function (depId) {
              var data = [];
              for (var i in baseInfo.userListInfo) {
                  var item = baseInfo.userListInfo[i];
                  if (item.departmentId == depId) {
                      data.push(item);
                  }
              }
              return data;
          },
		  getDepartmentUserInfo:function(){
			    baseInfo.userAllListByDepartment = {};
				var userAllList=baseInfo.userListInfo;
				
				for (var Id in userAllList) {
					var item = userAllList[Id];
					if (baseInfo.userAllListByDepartment[item.departmentId] == undefined) {
						baseInfo.userAllListByDepartment[item.departmentId] = {};
						baseInfo.userAllListByDepartment[item.departmentId].DepartmentName = item.departmentId;
						
						baseInfo.userAllListByDepartment[item.departmentId].UserList = [];
						baseInfo.userAllListByDepartment[item.departmentId].UserList.push(item);
					}
					else {
						baseInfo.userAllListByDepartment[item.departmentId].UserList.push(item);
					}
				}
				//console.log(baseInfo.userAllListByDepartment);
				return baseInfo.userAllListByDepartment;
		  }
      };
  }])
  //基础信息
  .factory('$OrgInfo', ['$BPHttp', 'ApiUrl', function ($BPHttp, ApiUrl) {
      var baseInfo = {
          departmentListInfo: [],//部门列表
		  organizeListInfo: [],//公司列表
		  postListInfo: [],//岗位列表
		  jobListInfo: [],//职位列表
		  roleListInfo: []//角色列表
      };
      return {
          init: function () {
              $BPHttp.post({
                  "url": ApiUrl.getOrgInfoApi,
                  "isverify": true,
                  "success": function (data) {
					  if(data.status.code==0){
						  baseInfo.departmentListInfo = data.result.department;
						  baseInfo.organizeListInfo = data.result.organize;
						  baseInfo.postListInfo = data.result.post;
						  baseInfo.jobListInfo = data.result.userGroup;
						  baseInfo.roleListInfo = data.result.role;
					  }
                  }
              });
          },
          getDepartmentListInfo: function () {
              return baseInfo.departmentListInfo;
          },
          getOrganizeListInfo: function () {
              return baseInfo.organizeListInfo;
          },
		  getPostListInfo: function () {
              return baseInfo.postListInfo;
          },
		  getJobListInfo: function () {
              return baseInfo.jobListInfo;
          },
		  getRoleListInfo: function () {
              return baseInfo.roleListInfo;
          }
      };
  }])
;
